<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>性能监控仪表盘 - 个人云笔记</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .metric-card {
            transition: all 0.3s ease;
        }
        .metric-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        .status-ok { background-color: #10b981; }
        .status-warning { background-color: #f59e0b; }
        .status-error { background-color: #ef4444; }
        
        .chart-container {
            position: relative;
            height: 300px;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-sm border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <h1 class="text-xl font-semibold text-gray-900">性能监控仪表盘</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="refreshBtn" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors">
                        刷新数据
                    </button>
                    <button id="resetMetricsBtn" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition-colors">
                        重置指标
                    </button>
                    <a href="/index.html" class="text-gray-600 hover:text-gray-900">返回主页</a>
                </div>
            </div>
        </div>
    </nav>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- 系统状态概览 -->
        <div class="mb-8">
            <h2 class="text-2xl font-bold text-gray-900 mb-4">系统状态概览</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <!-- 系统状态 -->
                <div class="metric-card bg-white rounded-lg shadow p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <div id="systemStatus" class="status-indicator status-ok"></div>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-gray-500">系统状态</p>
                            <p id="systemStatusText" class="text-lg font-semibold text-gray-900">正常</p>
                        </div>
                    </div>
                </div>

                <!-- 运行时间 -->
                <div class="metric-card bg-white rounded-lg shadow p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <svg class="h-8 w-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-gray-500">运行时间</p>
                            <p id="uptime" class="text-lg font-semibold text-gray-900">-</p>
                        </div>
                    </div>
                </div>

                <!-- 总请求数 -->
                <div class="metric-card bg-white rounded-lg shadow p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <svg class="h-8 w-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                            </svg>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-gray-500">总请求数</p>
                            <p id="totalRequests" class="text-lg font-semibold text-gray-900">-</p>
                        </div>
                    </div>
                </div>

                <!-- 成功率 -->
                <div class="metric-card bg-white rounded-lg shadow p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <svg class="h-8 w-8 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-gray-500">成功率</p>
                            <p id="successRate" class="text-lg font-semibold text-gray-900">-</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 性能指标 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- 内存使用情况 -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">内存使用情况</h3>
                <div class="chart-container">
                    <canvas id="memoryChart"></canvas>
                </div>
                <div class="mt-4 grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <span class="text-gray-500">已使用:</span>
                        <span id="memoryUsed" class="font-semibold">-</span>
                    </div>
                    <div>
                        <span class="text-gray-500">使用率:</span>
                        <span id="memoryPercentage" class="font-semibold">-</span>
                    </div>
                </div>
            </div>

            <!-- CPU使用情况 -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">CPU使用情况</h3>
                <div class="chart-container">
                    <canvas id="cpuChart"></canvas>
                </div>
                <div class="mt-4 grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <span class="text-gray-500">CPU使用率:</span>
                        <span id="cpuUsage" class="font-semibold">-</span>
                    </div>
                    <div>
                        <span class="text-gray-500">负载平均:</span>
                        <span id="loadAverage" class="font-semibold">-</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 响应时间和数据库 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- 响应时间 -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">响应时间</h3>
                <div class="space-y-3">
                    <div class="flex justify-between">
                        <span class="text-gray-500">平均响应时间:</span>
                        <span id="avgResponseTime" class="font-semibold">-</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">数据库查询时间:</span>
                        <span id="avgQueryTime" class="font-semibold">-</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">慢查询数:</span>
                        <span id="slowQueries" class="font-semibold">-</span>
                    </div>
                </div>
            </div>

            <!-- 数据库连接 -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">数据库连接</h3>
                <div class="space-y-3">
                    <div class="flex justify-between">
                        <span class="text-gray-500">连接状态:</span>
                        <span id="dbStatus" class="font-semibold">-</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">活跃连接:</span>
                        <span id="activeConnections" class="font-semibold">-</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">总连接数:</span>
                        <span id="totalConnections" class="font-semibold">-</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">空闲连接:</span>
                        <span id="idleConnections" class="font-semibold">-</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 警告信息 -->
        <div id="alertsContainer" class="mb-8" style="display: none;">
            <h3 class="text-lg font-semibold text-red-600 mb-4">⚠️ 系统警告</h3>
            <div id="alertsList" class="space-y-2"></div>
        </div>

        <!-- 日志统计 -->
        <div class="bg-white rounded-lg shadow p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">日志统计</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="text-center">
                    <p class="text-2xl font-bold text-blue-600" id="logFiles">-</p>
                    <p class="text-sm text-gray-500">日志文件数</p>
                </div>
                <div class="text-center">
                    <p class="text-2xl font-bold text-green-600" id="logSize">-</p>
                    <p class="text-sm text-gray-500">总大小</p>
                </div>
                <div class="text-center">
                    <p class="text-2xl font-bold text-purple-600" id="logPath">-</p>
                    <p class="text-sm text-gray-500">日志路径</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        class PerformanceDashboard {
            constructor() {
                this.memoryChart = null;
                this.cpuChart = null;
                this.refreshInterval = null;
                this.init();
            }

            init() {
                this.setupCharts();
                this.setupEventListeners();
                this.startAutoRefresh();
                this.loadData();
            }

            setupCharts() {
                // 内存使用图表
                const memoryCtx = document.getElementById('memoryChart').getContext('2d');
                this.memoryChart = new Chart(memoryCtx, {
                    type: 'doughnut',
                    data: {
                        labels: ['已使用', '可用'],
                        datasets: [{
                            data: [0, 100],
                            backgroundColor: ['#ef4444', '#e5e7eb'],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });

                // CPU使用图表
                const cpuCtx = document.getElementById('cpuChart').getContext('2d');
                this.cpuChart = new Chart(cpuCtx, {
                    type: 'doughnut',
                    data: {
                        labels: ['使用中', '空闲'],
                        datasets: [{
                            data: [0, 100],
                            backgroundColor: ['#3b82f6', '#e5e7eb'],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }

            setupEventListeners() {
                document.getElementById('refreshBtn').addEventListener('click', () => {
                    this.loadData();
                });

                document.getElementById('resetMetricsBtn').addEventListener('click', () => {
                    this.resetMetrics();
                });
            }

            startAutoRefresh() {
                this.refreshInterval = setInterval(() => {
                    this.loadData();
                }, 10000); // 每10秒刷新一次
            }

            async loadData() {
                try {
                    const token = localStorage.getItem('authToken');
                    if (!token) {
                        window.location.href = '/login.html';
                        return;
                    }

                    const response = await fetch('/api/admin/metrics', {
                        headers: {
                            'Authorization': `Bearer ${token}`
                        }
                    });

                    if (response.status === 401) {
                        window.location.href = '/login.html';
                        return;
                    }

                    const data = await response.json();
                    if (data.success) {
                        this.updateDashboard(data.data);
                    }
                } catch (error) {
                    console.error('加载性能数据失败:', error);
                    this.showError('加载数据失败');
                }
            }

            updateDashboard(data) {
                const { performance, database, logging } = data;
                const { summary, details, alerts } = performance;

                // 更新系统状态
                this.updateSystemStatus(alerts);
                
                // 更新概览指标
                document.getElementById('uptime').textContent = summary.uptime;
                document.getElementById('totalRequests').textContent = summary.totalRequests;
                document.getElementById('successRate').textContent = summary.successRate;

                // 更新内存信息
                const memoryUsed = details.memory.percentage;
                document.getElementById('memoryUsed').textContent = 
                    `${(details.memory.heap.used / 1024 / 1024).toFixed(2)} MB`;
                document.getElementById('memoryPercentage').textContent = 
                    `${memoryUsed.toFixed(1)}%`;
                
                this.memoryChart.data.datasets[0].data = [memoryUsed, 100 - memoryUsed];
                this.memoryChart.update();

                // 更新CPU信息
                const cpuUsage = details.cpu.usage;
                document.getElementById('cpuUsage').textContent = `${cpuUsage.toFixed(1)}%`;
                document.getElementById('loadAverage').textContent = 
                    details.cpu.loadAverage.map(l => l.toFixed(2)).join(', ');
                
                this.cpuChart.data.datasets[0].data = [cpuUsage, 100 - cpuUsage];
                this.cpuChart.update();

                // 更新响应时间
                document.getElementById('avgResponseTime').textContent = summary.averageResponseTime;
                document.getElementById('avgQueryTime').textContent = 
                    `${details.database.averageQueryTime.toFixed(2)}ms`;
                document.getElementById('slowQueries').textContent = details.database.slowQueries;

                // 更新数据库连接
                document.getElementById('dbStatus').textContent = 
                    database.connected ? '已连接' : '未连接';
                document.getElementById('activeConnections').textContent = database.activeConnections;
                document.getElementById('totalConnections').textContent = database.totalConnections;
                document.getElementById('idleConnections').textContent = database.idleConnections;

                // 更新警告信息
                this.updateAlerts(alerts);

                // 更新日志统计
                if (logging && !logging.error) {
                    document.getElementById('logFiles').textContent = logging.totalFiles;
                    document.getElementById('logSize').textContent = logging.totalSizeFormatted;
                    document.getElementById('logPath').textContent = logging.logPath.split('/').pop();
                }
            }

            updateSystemStatus(alerts) {
                const statusIndicator = document.getElementById('systemStatus');
                const statusText = document.getElementById('systemStatusText');

                if (alerts.length === 0) {
                    statusIndicator.className = 'status-indicator status-ok';
                    statusText.textContent = '正常';
                } else {
                    const hasError = alerts.some(alert => alert.type === 'storage' || alert.value > 90);
                    if (hasError) {
                        statusIndicator.className = 'status-indicator status-error';
                        statusText.textContent = '异常';
                    } else {
                        statusIndicator.className = 'status-indicator status-warning';
                        statusText.textContent = '警告';
                    }
                }
            }

            updateAlerts(alerts) {
                const container = document.getElementById('alertsContainer');
                const list = document.getElementById('alertsList');

                if (alerts.length === 0) {
                    container.style.display = 'none';
                } else {
                    container.style.display = 'block';
                    list.innerHTML = alerts.map(alert => `
                        <div class="bg-red-50 border border-red-200 rounded-lg p-3">
                            <div class="flex">
                                <div class="flex-shrink-0">
                                    <svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                                    </svg>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm text-red-800">${alert.message}</p>
                                </div>
                            </div>
                        </div>
                    `).join('');
                }
            }

            async resetMetrics() {
                try {
                    const token = localStorage.getItem('authToken');
                    const response = await fetch('/api/admin/metrics/reset', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        }
                    });

                    const data = await response.json();
                    if (data.success) {
                        this.showSuccess('性能指标已重置');
                        this.loadData();
                    } else {
                        this.showError('重置失败');
                    }
                } catch (error) {
                    console.error('重置指标失败:', error);
                    this.showError('重置失败');
                }
            }

            showSuccess(message) {
                // 简单的成功提示
                const toast = document.createElement('div');
                toast.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50';
                toast.textContent = message;
                document.body.appendChild(toast);
                
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 3000);
            }

            showError(message) {
                // 简单的错误提示
                const toast = document.createElement('div');
                toast.className = 'fixed top-4 right-4 bg-red-500 text-white px-4 py-2 rounded-lg shadow-lg z-50';
                toast.textContent = message;
                document.body.appendChild(toast);
                
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 3000);
            }
        }

        // 初始化仪表盘
        document.addEventListener('DOMContentLoaded', () => {
            new PerformanceDashboard();
        });
    </script>
</body>
</html>